package com.itheima.service.impl;

import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpMapper empMapper;


    @Override
    public PageResult<Clazz> getConditionPageList(int page, int pageSize, String name, LocalDate begin, LocalDate end) {
        Page<Clazz> clazzPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Clazz> queryWrapper = Wrappers.<Clazz>lambdaQuery()
                .like(StrUtil.isNotEmpty(name), Clazz::getName, name)
                .between(ObjUtil.isNotNull(begin) && ObjUtil.isNotNull(end), Clazz::getEndDate, begin, end);
        this.page(clazzPage, queryWrapper);
        List<Clazz> clazzList = clazzPage.getRecords();
        LocalDate now = LocalDate.now();
        // 设置班级状态

        clazzList.forEach(o -> {
            LocalDate beginDate = o.getBeginDate();
            LocalDate endDate = o.getEndDate();
            if(now.isBefore(beginDate)){
                o.setStatus("未开班");
            }else if(now.isAfter(beginDate) && now.isBefore(endDate)){
                o.setStatus("开班中");
            }else {
                o.setStatus("已结课");
            }
        });
        // 查询并设置班级的班主任名
        Map<Integer, String> empMaps = empMapper.selectList(null).stream().collect(Collectors.toMap(Emp::getId, Emp::getName));
        clazzList.forEach(o -> o.setMasterName(empMaps.get(o.getMasterId())));
        return new PageResult<>(clazzPage.getTotal(), clazzList);
    }
}
